<template>
  <div v-if="isRecomand" class="recomand-item">
    <div class="rec-content">{{ content }}</div>

    <div v-for="rec in recomandedList" :key="rec" class="str-wrapper">
      <div class="rec-str" @click="handleRecomandClick(rec)">
        {{ rec }}
      </div>
    </div>
    <div class="rec-more" v-if="showMore">......</div>
  </div>

  <div v-else class="chat-item" :class="['type-' + item.type]">
    <div ref="refBubble" class="bubble">
      <span style="white-space: pre-line; word-break: break-all">
        {{ displayContent }}
      </span>
      <span v-if="!expand && overlength" class="expand" @click="expandItem"> 展开</span>
      <div ref="refMenu" v-show="showMenu" @click="copyContent" class="press-menu">
        <img src="./icon-copy.png" />
        <div>复制</div>
      </div>
    </div>
  </div>

  <div v-if="isReport" class="report-btns">
    <div class="report-btn" @click="genReport">
      <img src="../assets/genrpt.png" />
      <span>生成报告</span>
    </div>
    <div class="report-btn" @click="copyContent">
      <img src="../assets/copy.png" />
      <span>复制</span>
    </div>
  </div>

  <div v-if="!!item.chartData" class="chart-item">
    <div class="chart-bubble">
      <div class="chart-title">{{ chartTitle }}</div>
      <div :id="chartId" class="chart-ins" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onLongPress } from '@vueuse/core'
import { EChartsType } from 'echarts'
import { lineChart, barChart } from './chart.js'
import { onClickOutside } from '@vueuse/core'
import { uniqueId } from 'lodash-es'
const { token } = useUserStore()
import { useUserStore } from '@/store'
import { useClipboard } from '@vueuse/core'
import { ITEM_RENDER_EVT } from 'element-plus/es/components/virtual-list/src/defaults'
import { showToast } from 'vant'

const props = defineProps<{
  item: TypeConversationItem,
  showMore?: boolean
}>()

const emit = defineEmits(['menu', 'recomand', 'report'])

const showMenu = ref(false)
const refBubble = ref<HTMLElement | null>(null)
const refMenu = ref<HTMLElement | null>(null)
const chartId = uniqueId()
const classId = computed(() => {
  return props.item.classId
})

const isRecomand = computed(() => {
  return classId.value == 5
})

const isReport = computed(() => {
  return classId.value == 6
})

const content = computed(() => {
  if (isRecomand.value) {
    return props.item.content.split('\n')[0]
  }
  return props.item.content
})

const recomandedList = computed(() => {
  const text = props.item.content
  if (!isRecomand.value) return []
  const arr = text.split('\n')
  if (arr.length < 2) return []
  const recs = arr[1]
  const ret = recs.split(' ').filter(r => r.trim() != '')
  return ret
})

const chartTitle = computed(() => {
  if (!props.item.chartData) return ''
  const chartDataObj = JSON.parse(props.item.chartData)
  return chartDataObj.series[0].label
})

let chartIns: EChartsType | null = null
const initChart = () => {
  if (!props.item.chartData) return
  console.log('initChart')
  const chartDataObj = JSON.parse(props.item.chartData)
  setTimeout(() => {
    const bt = chartDataObj.series[0].type

    const opt = {
      gridTop: '20px',
      gridLeft: '15px',
      gridRight: '20px',
      gridBottom: '0px'
    }
    if (bt == 'line') {
      chartIns = lineChart(chartId, chartDataObj, opt)
    } else {
      chartIns = barChart(chartId, chartDataObj, opt)
    }
  }, 0)
}

onMounted(() => {
  initChart()
  onLongPress(
    refBubble,
    (e: PointerEvent) => {
      e.preventDefault()
      if (!isRecomand.value && !isReport.value) {
        // report
        showMenu.value = true
      }
    },
    {
      modifiers: { prevent: true }
    }
  )
})

onUnmounted(() => {
  if (chartIns) {
    chartIns.dispose()
  }
})

const handleRecomandClick = str => {
  emit('recomand', str)
}

onClickOutside(refMenu, () => {
  showMenu.value = false
})

// const reportUrl = `${import.meta.env.VITE_APP_BASE_API}/${
//   import.meta.env.VITE_APP_SREVICE_NAME_CITY_MANAGEMENT
// }/qa/downloadReport?key=${props.id}&token=${token}`
const genReport = () => {
  // const a = document.createElement('a')
  // a.href = reportUrl
  // a.click()
  emit('report', props.item.id)
}

const { copy, isSupported, copied, text } = useClipboard({
  source: props.item.content,
  legacy: true
})
const copyContent = () => {
  showMenu.value = false
  copy(props.item.content)
    .then(() => {
      showToast('复制成功')
    })
    .catch(() => {
      showToast('复制失败')
    })
}

const expand = ref(false)
const overlength = computed(() => {
  return content.value.length > 80
})
const displayContent = computed(() => {
  if (expand.value) return content.value
  if (overlength.value) {
    return content.value.slice(0, 80) + '...'
  }

  return content.value
})

const expandItem = () => {
  expand.value = true
}
</script>

<style lang="less" scoped>
.report-btns {
  display: flex;
  justify-content: flex-end;
  .report-btn {
    margin-right: 16px;
    border-radius: 999px;
    background: #ffffff7f;
    border: 0.5px solid #ffffff;
    padding: 6px 11px;
    display: flex;
    align-items: center;
    img {
      width: 13px;
      height: 13px;
      margin-right: 4px;
    }
  }
}

.chart-item {
  padding: 10px 16px;
  font-size: 14px;
  display: flex;

  .chart-bubble {
    width: 100%;
    background: #ffffff;
    backdrop-filter: blur(2px);
    box-shadow: 0px 2.5px 7.5px 0px #508dd919;
    padding: 16px;
    border-radius: 12.5px;

    .chart-title {
      color: #212121;
      font-weight: bold;
      font-size: 14px;
    }

    .chart-ins {
      height: 150px;
      margin-top: 12.5px;
      // background: #efefef;
    }
  }
}
.recomand-item {
  width: 343px;
  border-radius: 12.5px 12.5px 12.5px 2.5px;
  background: #ffffff;
  backdrop-filter: blur(2px);
  box-shadow: 0px 2.5px 7.5px 0px #508dd919;
  margin-left: 16px;
  padding: 20px;
  box-sizing: border-box;

  .rec-content {
    color: #8898ab;
    font-weight: medium;
    font-size: 13px;
    line-height: normal;
    letter-spacing: 0px;
    text-align: left;
    margin-bottom: 3px;
  }

  .rec-more {
    text-align: center;
    font-weight: bold;
    color: #212121;
  }

  .str-wrapper {
    text-align: center;
    padding: 6px 0px;
  }
  .rec-str {
    padding: 8px 16px;
    border-radius: 999px;
    background: linear-gradient(90deg, #d1e8fc77 0%, #e2f0fc77 100%);
    color: #212121;
    font-weight: bold;
    font-size: 14px;
    line-height: normal;
    letter-spacing: 0px;
    text-align: left;
    display: inline-block;
  }
}
.chat-item {
  position: relative;
  z-index: 1; // above chat-item
  padding: 10px 16px;
  font-size: 14px;
  display: flex;

  .press-menu {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 100%;
    background: #4c4c4c;
    border-radius: 5px;
    color: #fff;
    font-weight: medium;
    font-size: 14px;
    text-align: center;
    padding: 13px 24px;
    &:after {
      content: '';
      position: absolute;
      width: 0px;
      height: 0px;
      left: calc(50% - 5px);
      border-bottom: 5px solid #4c4c4c;
      border-top: 5px solid transparent;
      border-left: 5px solid transparent;
      border-right: 5px solid transparent;
      top: -10px;
    }
    img {
      width: 20px;
      height: 20px;
    }
  }

  .bubble {
    padding: 16px;
    border-radius: 12.5px 12.5px 12.5px 2.5px;
    max-width: 325px;
    line-height: 1.2;
    color: #000;
    background-color: #fff;
    box-shadow: 0px 2.5px 7.5px 0px #508dd919;
    backdrop-filter: blur(2px);
    position: relative;
    .expand {
      color: #348aff;
    }
  }
}
</style>
